from flask import Flask, request, jsonify, render_template, send_from_directory
import os
import sqlite3
import json
import traceback
from backend.api.name_generator import generate_names
from backend.models import init_database, save_name_record

app = Flask(__name__, static_folder='frontend/static', template_folder='frontend')

# 初始化数据库
init_database()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/name/generate', methods=['POST'])
def name_generation():
    try:
        data = request.get_json()
        print(data)
        # 校验参数
        required_fields = ['surname', 'gender', 'birthDate', 'expectation']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({"status": 400, "message": f"缺少必要参数: {field}"}), 400
        
        # 调用取名函数
        names = generate_names(data)
        
        # 保存记录
        save_name_record(data, names)
        
        return jsonify({
            "status": 200,
            "message": "成功",
            "data": names
        })
    except Exception as e:
        print("发生异常:",traceback.format_exc())
        return jsonify({"status": 500, "message": f"服务器错误: {str(e)}"}), 500

@app.route('/static/<path:path>')
def send_static(path):
    return send_from_directory('frontend/static', path)

if __name__ == '__main__':
    app.run(debug=True, port=5000)
